conf.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. // conf.go - Functions for pacman.conf parsing.
  2. //
  3. // Copyright (c) 2013 The go-alpm Authors
  4. //
  5. // MIT Licensed. See LICENSE for details.
  6. package alpm
  7. import (
  8. "bufio"
  9. "bytes"
  10. "fmt"
  11. "io"
  12. "os"
  13. "reflect"
  14. "strconv"
  15. "strings"
  16. "syscall"
  17. )
  18. type PacmanOption uint
  19. const (
  20. ConfUseSyslog PacmanOption = 1 << iota
  21. ConfColor
  22. ConfTotalDownload
  23. ConfCheckSpace
  24. ConfVerbosePkgLists
  25. ConfILoveCandy
  26. )
  27. var optionsMap = map[string]PacmanOption{
  28. "UseSyslog": ConfUseSyslog,
  29. "Color": ConfColor,
  30. "TotalDownload": ConfTotalDownload,
  31. "CheckSpace": ConfCheckSpace,
  32. "VerbosePkgLists": ConfVerbosePkgLists,
  33. "ILoveCandy": ConfILoveCandy,
  34. }
  35. // PacmanConfig is a type for holding pacman options parsed from pacman
  36. // configuration data passed to ParseConfig.
  37. type PacmanConfig struct {
  38. RootDir string
  39. DBPath string
  40. CacheDir []string
  41. HookDir []string
  42. GPGDir string
  43. LogFile string
  44. HoldPkg []string
  45. IgnorePkg []string
  46. IgnoreGroup []string
  47. Include []string
  48. Architecture string
  49. XferCommand string
  50. NoUpgrade []string
  51. NoExtract []string
  52. CleanMethod []string
  53. SigLevel SigLevel
  54. LocalFileSigLevel SigLevel
  55. RemoteFileSigLevel SigLevel
  56. UseDelta float64
  57. Options PacmanOption
  58. Repos []RepoConfig
  59. }
  60. // RepoConfig is a type that stores the signature level of a repository
  61. // specified in the pacman config file.
  62. type RepoConfig struct {
  63. Name string
  64. SigLevel SigLevel
  65. Servers []string
  66. }
  67. // Constants for pacman configuration parsing
  68. const (
  69. tokenSection = iota
  70. tokenKey
  71. tokenComment
  72. )
  73. type iniToken struct {
  74. Type uint
  75. Name string
  76. Values []string
  77. }
  78. type confReader struct {
  79. *bufio.Reader
  80. Lineno uint
  81. }
  82. // newConfReader reads from the io.Reader if it is buffered and returns a
  83. // confReader containing the number of bytes read and 0 for the first line. If
  84. // r is not a buffered reader, a new buffered reader is created using r as its
  85. // input and returned.
  86. func newConfReader(r io.Reader) confReader {
  87. if buf, ok := r.(*bufio.Reader); ok {
  88. return confReader{buf, 0}
  89. }
  90. buf := bufio.NewReader(r)
  91. return confReader{buf, 0}
  92. }
  93. func (rdr *confReader) ParseLine() (tok iniToken, err error) {
  94. line, overflow, err := rdr.ReadLine()
  95. switch {
  96. case err != nil:
  97. return
  98. case overflow:
  99. err = fmt.Errorf("line %d too long", rdr.Lineno)
  100. return
  101. }
  102. rdr.Lineno++
  103. line = bytes.TrimSpace(line)
  104. if len(line) == 0 {
  105. tok.Type = tokenComment
  106. return
  107. }
  108. switch line[0] {
  109. case '#':
  110. tok.Type = tokenComment
  111. return
  112. case '[':
  113. closing := bytes.IndexByte(line, ']')
  114. if closing < 0 {
  115. err = fmt.Errorf("missing ']' is section name at line %d", rdr.Lineno)
  116. return
  117. }
  118. tok.Name = string(line[1:closing])
  119. if closing+1 < len(line) {
  120. err = fmt.Errorf("trailing characters %q after section name %s",
  121. line[closing+1:], tok.Name)
  122. return
  123. }
  124. return
  125. default:
  126. tok.Type = tokenKey
  127. if idx := bytes.IndexByte(line, '='); idx >= 0 {
  128. optname := bytes.TrimSpace(line[:idx])
  129. values := bytes.Split(line[idx+1:], []byte{' '})
  130. tok.Name = string(optname)
  131. tok.Values = make([]string, 0, len(values))
  132. for _, word := range values {
  133. word = bytes.TrimSpace(word)
  134. if len(word) > 0 {
  135. tok.Values = append(tok.Values, string(word))
  136. }
  137. }
  138. } else {
  139. // boolean option
  140. tok.Name = string(line)
  141. tok.Values = nil
  142. }
  143. return
  144. }
  145. }
  146. func ParseConfig(r io.Reader) (conf PacmanConfig, err error) {
  147. rdr := newConfReader(r)
  148. rdrStack := []confReader{rdr}
  149. conf.SetDefaults()
  150. confReflect := reflect.ValueOf(&conf).Elem()
  151. var currentSection string
  152. var curRepo *RepoConfig
  153. lineloop:
  154. for {
  155. line, err := rdr.ParseLine()
  156. // fmt.Printf("%+v\n", line)
  157. switch err {
  158. case io.EOF:
  159. // pop reader stack.
  160. l := len(rdrStack)
  161. if l == 1 {
  162. break lineloop
  163. }
  164. rdr = rdrStack[l-2]
  165. rdrStack = rdrStack[:l-1]
  166. default:
  167. break lineloop
  168. case nil:
  169. // Ok.
  170. }
  171. switch line.Type {
  172. case tokenComment:
  173. case tokenSection:
  174. currentSection = line.Name
  175. if currentSection != "options" {
  176. conf.Repos = append(conf.Repos, RepoConfig{})
  177. curRepo = &conf.Repos[len(conf.Repos)-1]
  178. curRepo.Name = line.Name
  179. }
  180. case tokenKey:
  181. switch line.Name {
  182. case "SigLevel":
  183. // TODO: implement SigLevel parsing.
  184. continue lineloop
  185. case "Server":
  186. curRepo.Servers = append(curRepo.Servers, line.Values...)
  187. continue lineloop
  188. case "Include":
  189. f, err := os.Open(line.Values[0])
  190. if err != nil {
  191. err = fmt.Errorf("error while processing Include directive at line %d: %s",
  192. rdr.Lineno, err)
  193. break lineloop
  194. }
  195. rdr = newConfReader(f)
  196. rdrStack = append(rdrStack, rdr)
  197. continue lineloop
  198. case "UseDelta":
  199. if len(line.Values) > 0 {
  200. deltaRatio, err := strconv.ParseFloat(line.Values[0], 64)
  201. if err != nil {
  202. break lineloop
  203. }
  204. conf.UseDelta = deltaRatio
  205. }
  206. continue lineloop
  207. }
  208. if currentSection != "options" {
  209. err = fmt.Errorf("option %s outside of [options] section, at line %d",
  210. line.Name, rdr.Lineno)
  211. break lineloop
  212. }
  213. // main options.
  214. if opt, ok := optionsMap[line.Name]; ok {
  215. // boolean option.
  216. conf.Options |= opt
  217. } else {
  218. // key-value option.
  219. fld := confReflect.FieldByName(line.Name)
  220. if !fld.IsValid() || !fld.CanAddr() {
  221. _ = fmt.Errorf("unknown option at line %d: %s", rdr.Lineno, line.Name)
  222. continue
  223. }
  224. switch fieldP := fld.Addr().Interface().(type) {
  225. case *string:
  226. // single valued option.
  227. *fieldP = strings.Join(line.Values, " ")
  228. case *[]string:
  229. //many valued option.
  230. *fieldP = append(*fieldP, line.Values...)
  231. }
  232. }
  233. }
  234. }
  235. if len(conf.CleanMethod) == 0 {
  236. conf.CleanMethod = []string{"KeepInstalled"}
  237. }
  238. if len(conf.CacheDir) == 0 {
  239. conf.CacheDir = []string{"/var/cache/pacman/pkg/"} //should only be set if the config does not specify this
  240. }
  241. return conf, err
  242. }
  243. func (conf *PacmanConfig) SetDefaults() {
  244. conf.RootDir = "/"
  245. conf.DBPath = "/var/lib/pacman"
  246. conf.DBPath = "/var/lib/pacman/"
  247. conf.HookDir = []string{"/etc/pacman.d/hooks/"} //should be added to whatever the config states
  248. conf.GPGDir = "/etc/pacman.d/gnupg/"
  249. conf.LogFile = "/var/log/pacman.log"
  250. conf.UseDelta = 0.7
  251. conf.SigLevel = SigPackage | SigPackageOptional | SigDatabase | SigDatabaseOptional
  252. conf.LocalFileSigLevel = SigUseDefault
  253. conf.RemoteFileSigLevel = SigUseDefault
  254. }
  255. func getArch() (string, error) {
  256. var uname syscall.Utsname
  257. err := syscall.Uname(&uname)
  258. if err != nil {
  259. return "", err
  260. }
  261. var arch [65]byte
  262. for i, c := range uname.Machine {
  263. if c == 0 {
  264. return string(arch[:i]), nil
  265. }
  266. arch[i] = byte(c)
  267. }
  268. return string(arch[:]), nil
  269. }
  270. func (conf *PacmanConfig) CreateHandle() (*Handle, error) {
  271. h, err := Init(conf.RootDir, conf.DBPath)
  272. if err != nil {
  273. return nil, err
  274. }
  275. if conf.Architecture == "auto" {
  276. conf.Architecture, err = getArch()
  277. if err != nil {
  278. return nil, fmt.Errorf("architecture is 'auto' but couldn't uname()")
  279. }
  280. }
  281. for _, repoconf := range conf.Repos {
  282. // TODO: set SigLevel
  283. db, err := h.RegisterSyncDb(repoconf.Name, 0)
  284. if err == nil {
  285. for i, addr := range repoconf.Servers {
  286. addr = strings.Replace(addr, "$repo", repoconf.Name, -1)
  287. addr = strings.Replace(addr, "$arch", conf.Architecture, -1)
  288. repoconf.Servers[i] = addr
  289. }
  290. db.SetServers(repoconf.Servers)
  291. }
  292. }
  293. err = h.SetCacheDirs(conf.CacheDir...)
  294. if err != nil {
  295. return nil, err
  296. }
  297. // add hook directories 1-by-1 to avoid overwriting the system directory
  298. for _, dir := range conf.HookDir {
  299. err = h.AddHookDir(dir)
  300. if err != nil {
  301. return nil, err
  302. }
  303. }
  304. err = h.SetGPGDir(conf.GPGDir)
  305. if err != nil {
  306. return nil, err
  307. }
  308. err = h.SetLogFile(conf.LogFile)
  309. if err != nil {
  310. return nil, err
  311. }
  312. err = h.SetIgnorePkgs(conf.IgnorePkg...)
  313. if err != nil {
  314. return nil, err
  315. }
  316. err = h.SetIgnoreGroups(conf.IgnoreGroup...)
  317. if err != nil {
  318. return nil, err
  319. }
  320. err = h.SetArch(conf.Architecture)
  321. if err != nil {
  322. return nil, err
  323. }
  324. h.SetNoUpgrades(conf.NoUpgrade...)
  325. if err != nil {
  326. return nil, err
  327. }
  328. h.SetNoExtracts(conf.NoExtract...)
  329. if err != nil {
  330. return nil, err
  331. }
  332. err = h.SetDefaultSigLevel(conf.SigLevel)
  333. if err != nil {
  334. return nil, err
  335. }
  336. err = h.SetLocalFileSigLevel(conf.LocalFileSigLevel)
  337. if err != nil {
  338. return nil, err
  339. }
  340. err = h.SetRemoteFileSigLevel(conf.RemoteFileSigLevel)
  341. if err != nil {
  342. return nil, err
  343. }
  344. err = h.SetDeltaRatio(conf.UseDelta)
  345. if err != nil {
  346. return nil, err
  347. }
  348. err = h.SetUseSyslog(conf.Options&ConfUseSyslog > 0)
  349. if err != nil {
  350. return nil, err
  351. }
  352. err = h.SetCheckSpace(conf.Options&ConfCheckSpace > 0)
  353. if err != nil {
  354. return nil, err
  355. }
  356. return h, nil
  357. }